import demo.AbstractDiscount;
import demo.impl.DirectDiscount;
import demo.impl.FewMoney2Buy;
import demo.impl.SubtractOff;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

/**
 * @author ZhouWeiBo
 * @create 2022/6/7
 */
public class App {
    private static final Map<Integer, AbstractDiscount> DISCOUNTS = new LinkedHashMap<>();

    public static void main(String[] args) {
        /* 定义一个商品 */
        AtomicReference<BigDecimal> iPhonePrice = new AtomicReference<>(new BigDecimal(5999));
        /* 查询所有拥有的优惠卷 */
        List<AbstractDiscount> abstractDiscounts = getAllDiscountsByUserId();
        abstractDiscounts.forEach(abstractDiscount -> {
            iPhonePrice.set(abstractDiscount.discountAmount(iPhonePrice.get()));
        });
        /* 获取最后的价格 */
        System.out.println(iPhonePrice.get());
    }



    /**
     * 模仿数据库获取该用户拥有的所有优惠卷
     * @return
     */
    public static List<AbstractDiscount> getAllDiscountsByUserId(){
        initDiscounts();

        Set<AbstractDiscount> mineAbstractDiscounts = new LinkedHashSet<>();
        /* 随机获得未知数量的优惠卷 */
        int totalDiscountCount = new Random().nextInt(5);
        /* 随机获得优惠卷 */
        for (int i = 0; i< totalDiscountCount ; i++){
            int randomDiscountType = new Random().nextInt(DISCOUNTS.size());
            mineAbstractDiscounts.add(DISCOUNTS.get(randomDiscountType));
        }
        return mineAbstractDiscounts.stream().sorted(Comparator.comparing(AbstractDiscount::order)).collect(Collectors.toList());
    }

    public static void initDiscounts(){
        DISCOUNTS.clear();
        /* 95折优惠 */
        DISCOUNTS.put(0,new SubtractOff(new BigDecimal("0.95")));
        /* 85折优惠 */
        DISCOUNTS.put(1,new SubtractOff(new BigDecimal("0.85")));
        /* 5折优惠 */
        DISCOUNTS.put(2,new SubtractOff(new BigDecimal("0.50")));
        /* 1折优惠 */
        DISCOUNTS.put(3,new SubtractOff(new BigDecimal("0.10")));
        /* 1元购 */
        DISCOUNTS.put(4,new FewMoney2Buy(new BigDecimal(1)));
        /* 满101元减100元 */
        DISCOUNTS.put(5,new DirectDiscount(new BigDecimal(101),new BigDecimal(100)));
    }
}
